Class Nur.MNISV3.Common.Utils Extends %RegisteredObject [ Not ProcedureBlock ]
{

/// 返回公共JSON数据
/// Creator:JYW
/// CreatDate:2018-08-08
/// Input:msg 消息描述，msgcode 消息代码，status 结果状态
/// w ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson("成功","999999","0")
ClassMethod ReturnMsgJson(msg As %String, msgcode As %String, status As %String) As %String
{
    n (msg,msgcode,status)
    s json=##class(%ArrayOfDataTypes).%New()
    d json.SetAt($g(msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(status),"status")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
}

/// 返回公共JSON 对象
ClassMethod ReturnMsgJsonObj(msg As %String, msgcode As %String, status As %String) As %String
{
    n (msg,msgcode,status)
    s json=##class(%ArrayOfDataTypes).%New()
    d json.SetAt($g(msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(status),"status")
    q json
}

/// Creator：      fengliang 
/// CreatDate：    2021-03-22
/// Description:   返回公共数据流
/// w ##class(Nur.MNISV3.Common.Utils).ReturnMsgStream("成功","999999","0")
ClassMethod ReturnMsgStream(msg, msgcode, status) As %GlobalCharacterStream
{
    n (msg,msgcode,status)
    s curDateTime=$zd(+$h,3)_" "_$zt($p($h,",",2))
    s json=##class(%ArrayOfDataTypes).%New()
    d json.SetAt($g(msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(status),"status")
    d json.SetAt($g(curDateTime),"curDateTime")
    s dataStream=##class(%GlobalCharacterStream).%New()
    d ##class(Nur.MNISV3.Common.JSON).EncodeByStream(json,.dataStream)
    q dataStream
}

/// Creator：      fengliang 
/// CreatDate：    2021-03-22
/// Description:   将数据转换成流
/// w ##class(Nur.MNISV3.Common.Utils).DataToStream()
ClassMethod DataToStream(data) As %GlobalCharacterStream
{
    n (data)
    i '$IsObject(data) s dataObj = ##class(Nur.MNISV3.Common.JSON).Decode(data)
    e  s dataObj=data
    //已经是流对象,直接返回
    i $IsObject(dataObj) {
        i dataObj.%ClassName()="%GlobalCharacterStream" q dataObj
    }
    s dataStream=##class(%GlobalCharacterStream).%New()
    d ##class(Nur.MNISV3.Common.JSON).EncodeByStream(dataObj,.dataStream)   
    q dataStream
}

/// 创建一个模板对象
ClassMethod CreateModelInfo(id, title, buttons, modelList)
{
    n (id,title,buttons,modelList)
    s modelinfo=##class(%ArrayOfDataTypes).%New()
    d modelinfo.SetAt($g(buttons),"buttons")
    d modelinfo.SetAt($g(id),"id")
    d modelinfo.SetAt($g(title),"title")
    d modelinfo.SetAt($g(modelList),"modelList")
    q modelinfo
}

/// 获取entities中BarCode --- 参数: flag为空,只取最后一个; flag为1或Y, 取所有的
/// w ##class(Nur.MNISV3.Common.Utils).GetBarcodeByEntities("[{""barcode"":""0000000689"",""entity"":""patient"",""manual"":"""",""result"":""1217"",""scan"":""1""}]")
/// w ##class(Nur.MNISV3.Common.Utils).GetBarcodeByEntities("[{""barcode"":""1174||1169||128"",""entity"":""order"",""manual"":"""",""result"":"""",""scan"":""1""}]","order")
ClassMethod GetBarcodeByEntities(entities, type = "patient", flag = "")
{
    n (entities,type,flag)
    //s ^GRS("GetBarcodeByEntities",$h)=$lb(entities,type,flag)
    s barcodeOne="",barcodeAll=""
    q:entities="" "" // 不能为空
    i $isobject(entities) s entitiesObj=entities
    e  s entitiesObj=##class(Nur.MNISV3.Common.JSON).Decode(entities) 
    f idx=1:1:entitiesObj.Count(){
        s entity=entitiesObj.GetAt(idx).GetAt("entity")
        i entity=$g(type) { // entity类型 匹配
            s code=entitiesObj.GetAt(idx).GetAt("barcode")
            s result=entitiesObj.GetAt(idx).GetAt("result")
            s barcodeOne=code
            // 1,只取单个---带有result(如果是patient,result就诊号)
            i result'="" s barcodeOne=code_"^"_result
            // 2,取所有的
            i $g(flag)'="" {
                i barcodeAll="" s barcodeAll=code
                e  s barcodeAll=barcodeAll_"^"_code
            }
        }
    }
    i $g(flag)'="" q barcodeAll
    q barcodeOne
}

/// 移除entities中BarCode
/// 情况1: barCode不为空 + type为空,只移除barCode  情况2:barCode不为空 + type不为空,只移除type类型对应的barCode
/// 情况3: barCode为空 + type不为空,移除所有的type类型
/// w ##class(Nur.JSON).Encode(##class(Nur.MNISV3.Common.Utils).RemoveEntitiesByBarCode("[{""barcode"":""0000000689"",""entity"":""patient"",""manual"":"""",""result"":""1217"",""scan"":""1""}]","0000000689","patient"))
ClassMethod RemoveEntitiesByBarCode(entities, barCode = "", type = "")
{
    n (entities,barCode,type)
    s ^GRS("RemoveEntitiesByBarCode",$zts)=$lb(entities,barCode,type)
    s $zt="errrr"
    q:entities="" "" // 不能为空
    i $isobject(entities) s entitiesObj=entities
    e  s entitiesObj=##class(Nur.MNISV3.Common.JSON).Decode(entities) 
    f idx=entitiesObj.Count():-1:1 { //移除操作--倒序循环
        s entity=entitiesObj.GetAt(idx).GetAt("entity")
        s barcode=entitiesObj.GetAt(idx).GetAt("barcode")
        i ($g(type)'="")&&(entity=$g(type)) { // 1,指定type 类型 移除重复的
            i (barCode'="") {
                i barCode=barcode d entitiesObj.RemoveAt(idx)
            }else { // 2,指定type  移除所有的
                d entitiesObj.RemoveAt(idx)
            }
        }else { // 3,不指定type 直接移除重复的
            i barCode=barcode d entitiesObj.RemoveAt(idx)
        }
    }
   q entitiesObj
errrr
  w $ze,!
}

/// 将resultSet组装到obj对象中,并返回
ClassMethod ResultSet(resultSet As %ResultSet) As %ArrayOfDataTypes
{
    n (resultSet) 
    s Obj=##class(%ArrayOfDataTypes).%New()
    i '$IsObject(resultSet) q Obj
    f len=1:1:resultSet.GetColumnCount()
    {
         s ColumnName=resultSet.GetColumnName(len) 
         s Value=resultSet.GetDataByName(ColumnName)
         ; 模式语法是： n(pattern_element, pattern_element, ...) 表示匹配n次整个括号内的模式序列, 括号内用逗号 , 分隔两个子模式，代表 逻辑或 关系（满足任意一个即可）
         ; 前面都有一个`1(`，是分别对两个子模式都要求匹配一次 例如，`3("a")` 表示匹配连续三个"a"
         ; 第一个子模式：1"[".E1"]"
            ; 1"[" → 匹配 一个左方括号 [。
            ; E → 匹配 任意单个字符（E 是通配符）。
            ; 1"]" → 匹配 一个右方括号 ]。
          
         s match=Value?1(1"[".E1"]",1"{".E1"}")
         i match { // 将字符 转换对象
           s Value=##class(Nur.MNISV3.Common.JSON).Decode(Value)
         }
         d Obj.SetAt(Value,ColumnName)
    }
    q Obj
}

/// 将resultSet组装到List对象中,并返回
ClassMethod ResultSetToList(resultSet As %ResultSet) As %ListOfDataTypes
{
    n (resultSet)
    s List=##class(%ListOfDataTypes).%New()
    i '$IsObject(resultSet) q List
    while (resultSet.Next()){
        s obj= ..ResultSet(resultSet)
        d List.Insert(obj)
    }
    q List
}

/// 快速添加screenParts刷选
ClassMethod AddScreenPartObject(commonKey, keyCode, keyDesc, keyType, keyValue)
{
    s obj=##class(%ArrayOfDataTypes).%New()
    d obj.SetAt($g(commonKey),"commonKey")
    d obj.SetAt($g(keyCode),"keyCode")
    d obj.SetAt($g(keyDesc),"keyDesc")
    d obj.SetAt($g(keyType),"keyType")
    d obj.SetAt($g(keyValue),"keyValue")
    q obj
}

/// APP向服务器存变量
ClassMethod SetPDASetting(key As %String, value As %String, wardId As %String, userId As %String) As %String
{
    n (key,value,wardId,userId)
    s $zt="errSetPDASetting"
    i $g(key)'="" {  
        s ^DHCNurPDAMNISXHSet("PDA"_key,userId,wardId)=value  
    }
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson("成功","999999","0")
errSetPDASetting
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson($ze,"100018","-1")
}

/// APP获取服务量
ClassMethod GetPDASetting(key As %String, wardId As %String, userId As %String) As %String
{
    n (key,wardId,userId)
    s $zt="errGetPDASetting"
    s val=""
    i ($g(key)'="")&&$d(^DHCNurPDAMNISXHSet("PDA"_key)) {  
        s val= $g(^DHCNurPDAMNISXHSet("PDA"_key,userId,wardId))
    }
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(val,"999999","0")
errGetPDASetting
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson($ze,"100018","-1")
}

/// 判断一个字符串是否是正数
/// Input:data 要判断的字符串
/// w ##class(Nur.MNISV3.Common.Utils).ifPositiveNumber("测试")
ClassMethod IfPositiveNumber(data)
{
  n (data)
  s flag=1
  s piontNum=0  //小数点个数
  f len=1:1:$L(data) d
  .s char=$E(data,len,len)
  .i (($ZC(char)<48)||($ZC(char)>57))&(char'=".") s flag=0
  .i char="." s piontNum=piontNum+1
  i piontNum>1 s flag=0
  q flag
}

/// 获取当前时间
ClassMethod GetCurDateTime() As %String [ WebMethod ]
{
    s json=##class(%ArrayOfDataTypes).%New()
    d json.SetAt("","msg")
    d json.SetAt("99999","msgcode")
    d json.SetAt("0","status")
    d json.SetAt(+$h,"CurDate")
    d json.SetAt($p($h,",",2),"CurTime")
    s curDateTime=$zd(+$h,3)_" "_$zt($p($h,",",2))  
    s endDateTime=$zd(+$h+1,3)_" "_$zt($p($h,",",2))
    d json.SetAt($g(curDateTime),"curDateTime")
    d json.SetAt($zd(+$h,3)_" 00:00:00","stDateTime")
    d json.SetAt($zd(+$h,3)_" 23:59:59","endDateTime")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
}

/// 时间是否有效
/// w ##class(Nur.MNISV3.Common.Utils).ifValidTime(65302,60451)
ClassMethod IfValidTime(date, time) As %String
{
    s validTime="7200" //2个小时
    s curDate=+$h
    s curTime=$p($h,",",2)
    s timeDvalue=curDate*86400+curTime-(date*86400)-time
    i timeDvalue>validTime s validFlag=0  //无效
    e  s validFlag=1  //有效
    s json=##class(%ArrayOfDataTypes).%New()
    d json.SetAt("","msg")
    d json.SetAt("99999","msgcode")
    d json.SetAt("0","status")
    d json.SetAt(validFlag,"ValidFlag")
    s ret=##class(Nur.MNISV3.Common.JSON).Encode(json)
    q ret
}

/// 设置 医嘱查询时间
ClassMethod SetSchDateTime(user As %String, stdatetime As %String, enddatetime As %String) As %String
{
    s ^DHCPdaNurSCHSet("schSet","StDatTim",user)=stdatetime
    s ^DHCPdaNurSCHSet("schSet","EndDatTim",user)=enddatetime
    q "OK"
}

/// 清除 医嘱查询时间
ClassMethod DelSchDateTime(user) As %String
{
    //每次登陆清除
    k ^DHCPdaNurSCHSet("schSet","StDatTim",user)
    k ^DHCPdaNurSCHSet("schSet","EndDatTim",user)
    q ..GetSchDateTime(user)
}

/// 获取 医嘱查询时间
ClassMethod GetSchDateTime(user) As %String
{
    s stdatetime=$G(^DHCPdaNurSCHSet("schSet","StDatTim",user))
    s enddatetime=$G(^DHCPdaNurSCHSet("schSet","EndDatTim",user))
    if stdatetime="" s stdatetime=$ZD(+$H,3)_",00:00:00"
    if enddatetime="" s enddatetime=$ZD(+$H,3)_",23:59:59"

    q stdatetime_"^"_enddatetime
}

/// 获取新版本
ClassMethod GetNewVerion(Ward, Ip, curver = "") As %String
{
   s flag=0
   s flag=..GetUpdateFlag(Ward,curver,Ip)
   s url=""
   if (flag'=0)
   {
     s url=flag_"^https://"_Ip_"/imedical/web/MobileNurse.apk"
   }
   q url
}

/// W ##class(Nur.MNISV3.Common.Utils).GetUpdateFlag($c(0),"4","222.132.155.205:57772")
ClassMethod GetUpdateFlag(ward, curver = "", webIp = "") As %String
{
    n (ward,curver,webIp)
    s flag=0
    s recId=$O(^Nur.PdaUpgradeSetI("WARDID"," "_ward,""))
    q:recId="" 0
    i $d(^PAWARD(ward)) d  //新建病区可能需要自动插入
    .i $g(recId)="" d  
    ..s obj=##class(Nur.PdaUpgradeSet).%New()
    ..s obj.WardId=ward
    ..s obj.IfShow="N"
    ..s obj.NewVersion=curver
    ..s obj.webIP=webIp
    ..d obj.%Save()
    ..s recId=obj.%Id()
    if webIp'=""
    {
        s a=##class(Nur.PdaUpgradeSet).%OpenId(recId)
        s a.webIP=webIp
        d a.%Save()
    }
    s Str=##class(Nur.PdaUpgradeSet).getVal1(recId)

    s Uflag=$p(Str,"^",1)
    s version=$p(Str,"^",2)
    i version=curver s flag=0
    e  i Uflag="Y"  s flag=1
    i flag=1 q version
    q flag
}

/// http请求
/// http://10.1.20.214:8478/data/medical/device/bind/device/ward/bed?deviceTag=e89f6d7222be&wardld=2110&bedld=3
/// w ##class(Nur.NIS.Common.HttpClient).GetHttpContent("e89f6d7222be","2110","3")
ClassMethod GetHttpContent(deviceTag, wardld, bedld)
{
    
    // 1. 创建 HTTP 请求对象
    Set req = ##class(%Net.HttpRequest).%New()
    
    // 2. 设置目标服务器和端口 （不带 http:// 前缀）
    Set req.Server = "10.1.20.214"
    Set req.Port   = "8478"
    Set req.Timeout=5
    // 如果是 HTTPS，则加上：
    // Set req.Https = 1
    
    // 3. 插入 form-data 参数
    Do req.InsertFormData("deviceTag", deviceTag)
    Do req.InsertFormData("wardld",    wardld)
    Do req.InsertFormData("bedld",     bedld)
    
    // 4. 发送 POST 请求，路径从第一个 '/' 开始
    s url = "/data/medical/device/bind/device/ward/bed"
    Set status = req.Post(url)
    If $$$ISERR(status) {
        // 请求失败，打印状态码或错误信息
        Quit "请求失败，状态: "_ $System.Status.GetErrorText(status)
        
    }
    
    // 5. 读取并输出响应体
    Set resp = req.HttpResponse.Data.Read()
    q resp
}

}
